<template>
  <view class="container">
    <view class="header">
      <text class="title">客户资料上传</text>
    </view>

    <u-form :model="form" ref="uForm" :rules="rules" label-width="120">
      <!-- 身份证上传 -->
      <view class="form-section">
        <text class="section-title">身份证资料</text>
        <u-form-item label="身份证上传" prop="idCardDocs">
          <uni-file-picker
            v-model="form.idCardDocs"
            :limit="2"
            @select="onIdCardSelect"
            @delete="onIdCardDelete"
          ></uni-file-picker>
        </u-form-item>
      </view>

      <!-- 征信上传 -->
      <view class="form-section">
        <text class="section-title">征信资料</text>
        <u-form-item label="征信上传" prop="creditReport">
          <uni-file-picker
            v-model="form.creditReport"
            :limit="4"
            @select="onCreditReportSelect"
            @delete="onCreditReportDelete"
          ></uni-file-picker>
        </u-form-item>
      </view>

      <!-- 房产资料上传 -->
      <view class="form-section">
        <text class="section-title">房产资料</text>
        <u-form-item label="房产资料上传" prop="housePropertyDocs">
          <uni-file-picker
            v-model="form.housePropertyDocs"
            :limit="4"
            @select="onHousePropertySelect"
            @delete="onHousePropertyDelete"
          ></uni-file-picker>
        </u-form-item>
      </view>

      <!-- 其它上传 -->
      <view class="form-section">
        <text class="section-title">其他资料</text>
        <u-form-item label="其它上传" prop="otherDocs">
          <uni-file-picker
            v-model="form.otherDocs"
            :limit="4"
            @select="onOtherDocsSelect"
            @delete="onOtherDocsDelete"
          ></uni-file-picker>
        </u-form-item>
      </view>

      <!-- 保存按钮 -->
      <view class="button-group">
        <u-button type="primary" @click="submitForm" :loading="uploading">
          {{ uploading ? '上传中...' : '保存' }}
        </u-button>
        <u-button @click="navigateBack">返回</u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
import { store } from '@/uni_modules/uni-id-pages/common/store.js'
const db = uniCloud.database()

export default {
  data() {
    return {
      customerId: null,
      customerName: '',
      form: {
        // 文件上传字段
        idCardDocs: [],
        creditReport: [],
        housePropertyDocs: [],
        otherDocs: [],
      },
      rules: {
      },
      uploading: false,
    }
  },
  computed: {
    userInfo() {
      return store.userInfo
    }
  },
  onLoad(options) {
    if (options.customerId) {
      this.customerId = options.customerId
      this.loadCustomerData()
      this.loadUploadedFiles()
    }
  },
  onReady() {
  		//onReady 为uni-app支持的生命周期之一
      	this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    // 加载客户基本信息
    async loadCustomerData() {
      try {
        const res = await db.collection('mydb-customer').doc(this.customerId).get()
        if (res.result.data.length > 0) {
          this.customerName = res.result.data[0].name
        }
      } catch (error) {
        console.error('加载客户数据失败：', error)
        uni.showToast({ title: '加载客户数据失败', icon: 'none' })
      }
    },

    // 加载已上传的文件信息
    async loadUploadedFiles() {
      try {
        const res = await db.collection('mydb-customer-fields').where({ customerId: this.customerId }).get()
        if (res.result.data.length > 0) {
          const customerData = res.result.data[0]
          
          // 加载已上传的文件信息
          if (customerData.idCardDocs && customerData.idCardDocs.length > 0) {
            this.form.idCardDocs = customerData.idCardDocs
          }
          if (customerData.creditReport && customerData.creditReport.length > 0) {
            this.form.creditReport = customerData.creditReport
          }
          if (customerData.housePropertyDocs && customerData.housePropertyDocs.length > 0) {
            this.form.housePropertyDocs = customerData.housePropertyDocs
          }
          if (customerData.otherDocs && customerData.otherDocs.length > 0) {
            this.form.otherDocs = customerData.otherDocs
          }
          
        }
      } catch (error) {
        console.error('加载已上传文件信息失败：', error)
        uni.showToast({ title: '加载信息失败', icon: 'none' })
      }
    },

    // 身份证文件选择处理
    onIdCardSelect(e) {
    },

    // 身份证文件删除处理
    onIdCardDelete(e) {
    },

    // 征信文件选择处理
    onCreditReportSelect(e) {
    },

    // 征信文件删除处理
    onCreditReportDelete(e) {
    },

    // 房产文件选择处理
    onHousePropertySelect(e) {
    },

    // 房产文件删除处理
    onHousePropertyDelete(e) {
    },

    // 其他文件选择处理
    onOtherDocsSelect(e) {
    },

    // 其他文件删除处理
    onOtherDocsDelete(e) {
    },
    // 提交表单
    async submitForm() {
      try {
   
        this.uploading = true
        // 准备要保存的数据
        const updateData = {
          customerId: this.customerId,
          idCardDocs: this.form.idCardDocs,
          creditReport: this.form.creditReport,
          housePropertyDocs: this.form.housePropertyDocs,
          otherDocs: this.form.otherDocs,
          lastUpdateBy: this.userInfo._id,
          updateTime: Date.now()
        }

        // 查找是否存在该客户的记录
        const existingRecord = await db.collection('mydb-customer-fields').where({ customerId: this.customerId }).get()

        if (existingRecord.result.data.length > 0) {
          // 更新现有记录
          await db.collection('mydb-customer-fields').doc(existingRecord.result.data[0]._id).update(updateData)
        } else {
          // 创建新记录
          await db.collection('mydb-customer-fields').add(updateData)
        }

        uni.showToast({ title: '保存成功' })
        uni.showModal({
          title: '提示',
          content: '是否自动匹配产品',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/customer/matchProduct?customerId=' + this.customerId
              })
            }
          }
        })
      } catch (error) {
        console.error('提交表单失败：', error)
        uni.showToast({ title: `保存失败：${error.message}`, icon: 'none' })
      } finally {
        this.uploading = false
      }
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
  border-left: 6rpx solid #1989fa;
  padding-left: 15rpx;
}

.note-input {
  margin-top: 10rpx;
  border: 1px solid #e4e7ed;
  border-radius: 6rpx;
  padding: 0 20rpx;
}

.button-group {
  margin-top: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 调整uni-file-picker的样式 */
.uni-file-picker {
  margin-top: 10rpx;
}
</style>